<template>
  <div class="update-avatar">
    <img class="image" :src="image" alt="" ref="image">
    <van-nav-bar
      class="tool"
      left-text="返回"
      right-text="确定"
      @click-left="$emit('close')"
      @click-right="onConfirm"
    />
  </div>
</template>

<script>
import {updateUserPhoto} from '@/api/user'
// 引入裁剪图片的库
import 'cropperjs/dist/cropper.css'
import Cropper from 'cropperjs'


  export default {
    props:{
      file:{
        // type:Object,
        required:true
      }
    },
    data() {
      return {
        image:window.URL.createObjectURL(this.file),
        cropper:null
      }
    },
    mounted() {
      const image = this.$refs.image
        this.cropper = new Cropper(image, {
          viewMode: 1, // 查看模式
          dragMode: 'move', // 拖动模式
          aspectRatio: 1, // 截图比例
          // autoCropArea: 1, // 自动区域
          cropBoxMovable: false, // 不允许截图区域移动
          cropBoxResizable: false, // 不允许截图区域缩放
          modal: true, // 显示阴影区域
          background: false, // 关闭背景
          movable: true, // 允许移动
          // ...this.cropperOptions
        })
    },
    methods: {
      async onConfirm(){
        this.$toast.loading({
          message:'保存中...',
          forbidclick:true
        })
        const file = await this.getCroppedCanvas()
        const fd = new FormData()
        fd.append('photo', file)
        await updateUserPhoto(fd)
        this.$toast.success('保存成功')
        this.$emit('update-photo', window.URL.createObjectURL(file))
        this.$emit('close')
      },
      getCroppedCanvas(){
        return new Promise(resolve => {
          this.cropper.getCroppedCanvas().toBlob((blob) => {
            resolve(blob)
          })
        })
      }
    },
  }
</script>

<style lang="less" scoped>
  .tool{
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    background-color: #000;

  }
  .image{
    display: block;
    max-width: 100%;
  }
  /deep/.van-nav-bar__text{
    color: #fff;
    font-size: 16px;
  }
</style>